package com.naizhuai.ui.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.UserManageDataApiStore;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.SendSms;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.ValidateUtil;
import com.naizhuai.util.ViewUtils;

import butterknife.BindView;
import butterknife.OnClick;

public class UpdatePasswordActivity extends SwipeBackActivity {
    public static final int COUNTDOWM_FACTOR = 60;
    public static final String PHONENUMBER = "phonenumber";
    @BindView(R.id.ed_phonenumber)
    EditText ed_phonenumber;
    @BindView(R.id.ed_verification_code)
    EditText ed_verification_code;
    @BindView(R.id.tv_verification_code)
    TextView tv_verification_code;

    @BindView(R.id.ed_password)
    EditText ed_password;
    @BindView(R.id.ed_password_confirm)
    EditText ed_password_confirm;
    UserManageDataApiStore mUserManageDataApiStore;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.btn_sure)
    Button btnSure;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    public static void start(Context context) {
        Intent intent = new Intent(context, UpdatePasswordActivity.class);
        if (context instanceof BaseActivity)
            ((BaseActivity) context).startActivityTransition(intent);
    }

    public static void start(Context context, String phoneNumber) {
        Intent intent = new Intent(context, UpdatePasswordActivity.class);
        intent.putExtra(PHONENUMBER, phoneNumber);
        if (context instanceof BaseActivity)
            ((BaseActivity) context).startActivityTransition(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    private void initData() {
        if (mUserManageDataApiStore == null) {
            mUserManageDataApiStore = UserManageDataApiStoreIml.getInstance();
        }
        if (!TextUtils.isEmpty(getStrExtra(PHONENUMBER))) {
            ed_phonenumber.setText(getStrExtra(PHONENUMBER));
            ed_phonenumber.setEnabled(false);
            title.setText(getString(R.string.forget_password));
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_update_password;
    }

    @OnClick(R.id.tv_verification_code)
    public void getVerifyingCode() {
        if (TextUtils.isEmpty(ViewUtils.text(ed_phonenumber))) {
            shortToast(getString(R.string.please_phonenumber));
            return;
        }
        showWaitDiaLog();
        mUserManageDataApiStore.sendSms(ViewUtils.text(ed_phonenumber), SendSms.UPDATEPASSWORD_CODE)
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(getString(R.string.action_fail));
                    }

                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if (ConstantsState.isResultOk(result)) {
                            shortToast(getString(R.string.sendok));
                            startCountDown(tv_verification_code);
                        } else {
                            shortToast(getString(R.string.sendfail));
                        }
                    }
                });
    }

    private void startCountDown(TextView view) {
        view.setEnabled(false);
        CountDownTimer timer = new CountDownTimer(COUNTDOWM_FACTOR * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                view.setText(getString(R.string.count_down_again_send, millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                view.setEnabled(true);
                view.setText(getString(R.string.again_send));
            }
        };
        timer.start();
    }

    @OnClick(R.id.btn_sure)
    public void sureUpdate() {
        try {
            checkInput();
            updateUserData();
        } catch (ValidateException e) {
            shortToast(e.getMessage());
        }
    }

    private void updateUserData() {
        String phonenumber = ViewUtils.text(ed_phonenumber);
        String verification_code = ViewUtils.text(ed_verification_code);
        String password = ViewUtils.text(ed_password);
        String password_confirm = ViewUtils.text(ed_password_confirm);
        showWaitDiaLog();
        mUserManageDataApiStore.resetpassword(phonenumber,
                verification_code, password, password_confirm)
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if ("0".equals(result)) {
                            shortToast(getString(R.string.sendfail));
                        } else {
                            shortToast(getString(R.string.update_password_success));
                            finish();
                        }
                    }
                });
    }

    private void checkInput() throws ValidateException {
        if (TextUtils.isEmpty(ViewUtils.text(ed_phonenumber))) {
            throw new ValidateException(getString(R.string.please_phonenumber));
        }
        if (!ValidateUtil.validateMobile(ViewUtils.text(ed_phonenumber))) {
            throw new ValidateException(getString(R.string.phone_format_error));
        }
        if (TextUtils.isEmpty(ViewUtils.text(ed_verification_code))) {
            throw new ValidateException(getString(R.string.please_identifying_code));
        }
        if (TextUtils.isEmpty(ViewUtils.text(ed_password))) {
            throw new ValidateException(getString(R.string.please_password));
        }

        if (TextUtils.isEmpty(ViewUtils.text(ed_password_confirm))) {
            throw new ValidateException(getString(R.string.password_confirm));
        }
        if (ViewUtils.text(ed_password).length() < 6) {
            throw new ValidateException(getString(R.string.password_length));
        }
        if (ViewUtils.text(ed_password_confirm).length() < 6) {
            throw new ValidateException(getString(R.string.password_length));
        }

        if (!ViewUtils.text(ed_password_confirm).equals(ViewUtils.text(ed_password))) {
            throw new ValidateException(getString(R.string.password_error));
        }

    }

}
